package hu.vpszd.beans;

import java.util.Set;

import hu.vpszd.entities.Role;
import hu.vpszd.entities.User;
import hu.vpszd.services.RoleService
import hu.vpszd.services.UserService

import javax.faces.bean.SessionScoped

import org.apache.log4j.Logger
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.dao.DataIntegrityViolationException
import org.springframework.security.authentication.encoding.Md5PasswordEncoder
import org.springframework.stereotype.Component

@Component("registrationBean")
@SessionScoped
class RegistrationBean implements Serializable {
	private static final Logger log = Logger.getLogger(RegistrationBean.class)

	@Autowired
	private RoleService roleService
	@Autowired
	private UserService userService
	@Autowired
	private Md5PasswordEncoder passwordEncoder

	User user = new User()
	
	Boolean referens = false
	Boolean biralo = false

	void register() {
		try {
			userService.create(user);
			user.roles.add(roleService.getUserRole())
			if(referens){
				user.roles.add(roleService.getReferensRole())
			}
			if(biralo){
				Role asd = new Role()
				asd = roleService.getBiraloRole()
				user.roles.add(asd)
//				user.roles.add(roleService.getBiraloRole())
			}
			user.password = passwordEncoder.encodePassword(user.password, "basicsalt")
			userService.save(user)
			user = new User();
			referens = false
			biralo = false
		} 
		catch (DataIntegrityViolationException divEx) {
			log.error("Sikertelen regisztráció!", divEx);
		}
		catch (Exception e) {
			log.fatal("Sikertelen regisztráció!", e);
		}
	}
	
	void reset() {
		user = new User()
		referens = false
		biralo = false
	}
	
	User getUser(){
		return user
	}
}
